import datetime
import json

import akshare as ak
import pandas as pd
import requests
from gm.api import get_previous_trading_date, history
from gm.enum import ADJUST_PREV
from pandas.io.json import json_normalize

from ..common.code import code_to_shse_szse_symbol
from ..common.constant import DATE_FORMAT_PARTTERN_Y_M_D, DATE_FORMAT_PARTTERN_YMD
from ..common.date import date_format


def first_ztb_before_ten_thirty(date):
    """
    10:30分之前的首板
    :param date:
    :return:
    """
    stock_zt_pool_em_df = ak.stock_zt_pool_em(date=date)
    stock_zt_pool_em_df = stock_zt_pool_em_df[
        (stock_zt_pool_em_df['首次封板时间'] <= '103000') & (stock_zt_pool_em_df['最后封板时间'] <= '103000') & (
                stock_zt_pool_em_df['炸板次数'] == 0) & (stock_zt_pool_em_df['连板数'] == 1)]
    return stock_zt_pool_em_df


def select_zt_5days(context):
    """
    5日内的涨停板
    :param context:
    :return:
    """
    stock_zt_pool_em_df = pd.DataFrame()

    pre_date = context.now.strftime("%Y-%m-%d")
    for i in range(5):
        if i != 0:
            pre_date = get_previous_trading_date(exchange='SZSE', date=pre_date)
        date = datetime.strptime(pre_date, "%Y-%m-%d").strftime('%Y%m%d')
        em_df = ak.stock_zt_pool_em(date=date)
        if i != 0:
            stock_zt_pool_em_df = pd.merge(stock_zt_pool_em_df, em_df, on=['代码'], how='outer')
        else:
            stock_zt_pool_em_df = em_df

    return stock_zt_pool_em_df


def lian_ban_floor(date):
    content = requests.get('https://data.10jqka.com.cn/dataapi/limit_up/continuous_limit_up?filter=HS&date=' + date)
    data = json.loads(content.text)
    for content in data['data']:
        var = content['code_list']


def nearly_zt_not_contains_today(context, days, is_contains_one_heng_zt):
    """
    :param days:
    :return:
    """
    pre_date = context.now.strftime("%Y-%m-%d")
    zt_stocks = pd.DataFrame(None, columns=['code', 'date', 'high', 'low'])
    for i in range(days):
        pre_date = get_previous_trading_date(exchange='SZSE', date=pre_date)
        date = date_format(str(pre_date), DATE_FORMAT_PARTTERN_Y_M_D, DATE_FORMAT_PARTTERN_YMD)
        em_df = ak.stock_zt_pool_em(date=date)
        filter_code_list = list()
        for stock in em_df['代码']:
            if stock in filter_code_list:
                continue
            if stock in list(zt_stocks['code']):
                filter_code_list.append(stock)
                continue
            full_code = code_to_shse_szse_symbol(stock)
            history_data = history(symbol=full_code, frequency='1d', start_time=pre_date, end_time=pre_date,
                                   fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
            if is_contains_one_heng_zt is False and history_data['high'].loc[len(history_data) - 1] == \
                    history_data['low'].loc[len(history_data) - 1]:
                filter_code_list.append(stock)
                continue
            data = {"code": stock, "date": pre_date, "high": history_data['high'].loc[len(history_data) - 1],
                    "low": history_data['low'].loc[len(history_data) - 1]}
            zt_stocks = zt_stocks.append(data, ignore_index=True)
    return zt_stocks


def zt_strength(date):
    """
    https://data.10jqka.com.cn/datacenterph/limitup/limtupInfo.html#/
    同花顺涨停聚焦

    :param date:
    :return:
    """
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/51.0.2704.63 Safari/537.36'}
    url = 'https://data.10jqka.com.cn/dataapi/limit_up/limit_up_pool?page=1&limit=100000&field=199112,10,9001,330323,330324,330325,9002,330329,133971,133970,1968584,3475914,9003,9004&filter=HS,GEM2STAR&date=' + date + '&order_field=330324&order_type=0'
    content = requests.get(url, headers=headers)
    data = json.loads(content.text)
    data = data['data']
    df = json_normalize(data['info'])
    df = df.rename(columns={'code': '代码'})
    return df


def recent_trading_day_zt_before_1030():
    today = datetime.date.today()
    trade_date_df = ak.tool_trade_date_hist_sina()
    trade_date_list = trade_date_df["trade_date"].astype(str).tolist()
    while str(today) not in trade_date_list:  # 如果当前日期不在交易日期列表内，则当前日期天数减一
        today = today - datetime.timedelta(days=1)
    today = date_format(str(today), DATE_FORMAT_PARTTERN_Y_M_D, DATE_FORMAT_PARTTERN_YMD)
    stock_zt_pool_em_df = ak.stock_zt_pool_em(date=today)
    if '首次封板时间' not in stock_zt_pool_em_df.columns:
        return pd.DataFrame(columns=['代码'])
    stock_zt_pool_em_df = stock_zt_pool_em_df[
        (stock_zt_pool_em_df['首次封板时间'] <= '103000') & (stock_zt_pool_em_df['最后封板时间'] <= '103000') & (
                stock_zt_pool_em_df['炸板次数'] == 0)]
    stock_zt_pool_codes = stock_zt_pool_em_df['代码']
    return stock_zt_pool_codes
